package com.huaxin.dss2.message;

import com.huaxin.dss2.data.DataService;
import com.huaxin.dss2.message.bean.DataMsgBean;
import com.huaxin.dss2.message.exception.SaveRealDataException;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.Message;

/**
 * 厂级数据推送
 * Created by HX-119 on 2014/6/27.
 */
@Component
@Slf4j
public class MessageListener implements javax.jms.MessageListener {
    
    @Autowired
    private DataService dataService;

    @Autowired
    private MessageCache messageCache;

    /**
     * 厂级数据消息通道
     * @param message 消息内容
     */
    @Override
    public void onMessage(final Message message) {
        try {
            if(StringUtils.isEmpty(message.getStringProperty("topicName")) || !StringUtils.equals(message.getStringProperty("topicName"),"data")) {
                return;
            }
            String text = ((ActiveMQTextMessage)message).getText();
            log.info("get a message!"+text);

            DataMsgBean dataMsgBean = dataService.updateDataMsgBean(MessageParser.parse(text));
            dataService.save(dataMsgBean);

            messageCache.putToCache(dataMsgBean);

        } catch (SaveRealDataException e) {
            log.error("保存数据时发生错误,重新启动服务后会重新接收该消息.");
            throw new RuntimeException(e);
        } catch (Exception e) {
            log.error("消息处理异常,重新启动服务后会重新接收该消息.");
            throw new RuntimeException(e);
        }
    }

}
